﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Routing;
using SimpleRest.Core.Routing;

namespace SimpleRest.Core.Extensions.Handlers
{
    public class RouteHandler : IHttpHandler
    {
        public bool IsReusable
        {
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
           // if (!RouteUtility.IsNativeRouteRegistrationEnabled)
           // {
                try
                {
                    var applicationPath = context.Request.Url.AbsolutePath;
                    if (applicationPath != "/")
                        applicationPath = applicationPath.Replace(context.Request.ApplicationPath, "").Replace('\\', '/').Trim(new char[] { '/' });

                    RouteData routeInfoData = RouteUtility.GetRouteData(applicationPath, context.Request.HttpMethod);

                    if (routeInfoData != null)
                    {
                        var httpContextBase = new HttpContextWrapper(context);
                        RequestContext requestContext = new RequestContext(httpContextBase, routeInfoData);
                        IHttpHandler handler = null;
                        handler = routeInfoData.RouteHandler.GetHttpHandler(requestContext);

                        if (handler != null)
                        {
                            handler.ProcessRequest(context);
                            context.Response.End();
                        }
                    }
                }
                catch (Exception ex)
                {
                    // let asp.net pipeline run through.
                }
           // }
        }
    }
}
